﻿/*!
* jQuery grid plugin: 
* 
* version 0.1 2010-11-08
* Requires jQuery v1.4.2 or later
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Authors: Kim Seoung Min
* Company : Kongyoung DB
*/
(function ($) {

    $.fn.SuperGrid = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.tooltip');
        }
    };

    var methods = {
        Uinit: function (url) {
            this.SuperGrid("init", GetJsonSync(url));
        },

        init: function (JsonForm) {

            var superGrid = $(this);
            superGrid.html("").addClass("superGrid");

            var superGrid_head = $("<div  class='head'></div>").appendTo(superGrid);
            var superGrid_body = $("<div  class='body'></div>").appendTo(superGrid);
            var superGrid_foot = $("<div  class='foot'><table  cellSpacing='0'><tr><td></td><td></td></tr></table></div>").appendTo(superGrid);
            var superGrid_dialog = $("<div class='dialog'></div>").appendTo(superGrid);

            var superGrid_head_tbl = $("<table cellSpacing='0' style='width:0px' ><thead></thead></table>").appendTo(superGrid_head);
            var superGrid_body_tbl = $("<table cellSpacing='0' style='width:0px' class='data'><tbody></tbody></table>").appendTo(superGrid_body);

            superGrid.height(JsonForm.height == undefined ? "300" : JsonForm.height);
            superGrid.width(JsonForm.width == undefined ? "100%" : JsonForm.width);


            var height = superGrid.outerHeight();
            height -= superGrid_head.outerHeight();
            height -= superGrid_foot.outerHeight();
            superGrid_body.height(height - 13);

            if (JsonForm.resize) {
                superGrid.resizable();
                superGrid.addClass("superGrid_reSize")
                superGrid.resize(function (e) {
                    var obj = $(this);
                    var height = obj.outerHeight();
                    height -= obj.find('.superGrid_head').outerHeight();
                    height -= obj.find('.superGrid_foot').outerHeight();
                    obj.find('.superGrid_body').height(height - 11);
                    $(this).find('.superGrid_head table').offset({ left: $(this).find('.superGrid_body').offset().left })
                });
            }
            superGrid_foot.hide();
            if (JsonForm.ShowBottom) {
                superGrid_foot.show();
            }

            // 페이지 스크롤이 생기면 바디와 해드를 동시에 움직이도록 설정한다.
            superGrid_body.scroll(function (e) {
                $(this).parent().find('.head table').offset({ left: $(this).find('table').offset().left })
            });


            //////////////////////////////////////////////////////
            var chkclass = JsonForm.ShowRowSelect ? 'show_td' : 'hidn_td';
            var IDclass = JsonForm.ShowRowNum ? 'show_td' : 'hidn_td';
            var CRUDclass = JsonForm.ShowCRUD ? 'show_td' : 'hidn_td';
            var colCount = JsonForm.colModel.length;
            var rowNum = JsonForm.rowNum;
            var th = "<td class='" + chkclass + " tdCHK'> <input type='checkbox' class='ChkAll' value='checkAll' /></td>";
            var td = "<td class='" + chkclass + " tdCHK'> <input type='checkbox' value='check' /></td>";
            th += "<td class='" + IDclass + " tdID'>No</td>";
            td += "<td class='" + IDclass + " tdID'>&nbsp;</td>";
            th += "<td class='" + CRUDclass + " tdCURD'>CRUD</td>";
            td += "<td class='" + CRUDclass + " tdCURD'>&nbsp;</td>";

            /// : 초기테이블 해드와 row를 생성한다 ////////////////////////////////////////////
            for (var i = 0; i < colCount; i++) {
                var _index = JsonForm.colModel[i].index;
                var _width = JsonForm.colModel[i].width;
                var _caption = JsonForm.colModel[i].name;
                var _align = JsonForm.colModel[i].align;
                var _type = JsonForm.colModel[i].type
                var _code = JsonForm.colModel[i].code

                var _tdCss = JsonForm.colModel[i].type == "hidden" ? "hidn_td" : "show_td"; //"hidn_td":"show_td";
                var _style = " style='width: " + _width + ";text-align:" + _align + ";' class='" + _tdCss + "'  field='" + _index + "' ftype= '" + _type + "' code= '" + _type + "'  ";

                th += "<td class='" + _tdCss + "' field='" + _index + "' style='width: " + _width + "' >" + _caption + "</td>";

                switch (_type) {
                    case 'integer':
                        td += "<td " + _style + "><input type='text' class='gridTextNum' value='' oldvalue = ''/></td>";
                        break;
                    case 'string':
                        td += "<td " + _style + "><input type='text' class='gridTextBox' value='' oldvalue = ''/></td>";
                        break;
                    case 'combo':
                        // 콤보박스 바인딩처리용 옵션리스트를 미리 정의하여 저장하여 둔다
                        if (_code != undefined && _code != "" && _code != null) {
                            var pl = new JSONClientParameters();
                            pl.add("CODETY", _code);
                            var jdata = PostJsonSync("/bzService/superboard.asmx/GETCOMCODE", pl);
                            var selHtml = "";
                            $.each(jdata, function (index, value) {
                                selHtml += String.format("<option value='{0}'>{1}</option>", value.CodeID, value.CodeNAME);
                            });
                            td += "<td " + _style + "><select class='gridCombo' value='' oldvalue = ''>" + selHtml + "</select></td>";
                        }
                        break;
                    default:
                        td += "<td " + _style + ">&nbsp;</td>";
                }
            }

            //// head 생성 ///////////////////////////////////////////////////////////////////////////////////////////////
            th = "<tr>" + th + "</tr>"; //-->> No 항목 + 설정된 항목 헤더 바인딩
            superGrid_head_tbl.html("").html(th);
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////

            ////// body 생성 /////////////////////////////////////////////////////////////////////////////////////////////
            td = "<tr>" + td + "</tr>";
            tb = "";
            for (var i = 0; i < rowNum; i++) { tb += td; }
            superGrid_body_tbl.html("").html(tb);

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // 제사용이 가능하도록 구조정보를 보관한다.
            $(this).data("formatData", JsonForm);
            $(this).data("TRdata", superGrid_body_tbl.find('> tbody tr:last'));
            $(this).data("DataBody", superGrid_body_tbl);
            $(this).data("dialog", superGrid.dialog);
            superGrid_body_tbl.find('tr').remove();
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            return this;
        },

        Config: function (e) {
            var JsonForm = $(this).data("formatData");
            var pl = new JSONClientParameters();
            pl.add("id", "");
            var _json = PostJsonSync(JsonForm.FigUrl, pl);

            $(this).data("dialog").html(_json);
            $(this).data("dialog").dialog({
                autoOpen: false,
                width: 200,
                modal: false,
                closeOnEscape: false,
                title: '표 환경 설정'
            });
            $(this).data("dialog").dialog('open');
        },

        MessageBox: function (msg) {
            $(this).data("dialog").html(msg);
            $(this).data("dialog").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                closeOnEscape: false,
                title: '알림',
                buttons: {
                    "OK": function () { $(this).dialog("close"); }
                }
            });
            $(this).data("dialog").dialog('open');
        },

        GetformatData: function () {
            return $(this).data("formatData");
        },

        ShowData0: function (pl) {
            $(this).data("filter", pl);
            var JsonForm = $(this).data("formatData");
            pl.add("pagecnt", JsonForm.rowNum);
            pl.add("viewpage", 1);
            pl.add("OrderStr", JsonForm.Orderby);
            var loader = jQuery('<div><img src="/image/spinner.gif" /><br>Loading...</div>');
            var _Obj = $(this);
            _Obj.find('.data').hide();
            loader.prependTo(_Obj.find('.data').parent());
            PostJsonData(JsonForm.ListUr, pl, function (data) {

                var _data = eval("data." + JsonForm.DataName);

                // doSomething(data, _Obj);
                _Obj.SuperGrid("ShowData", _data, data.TRCOUNT, data.VIEWPAGE, data.TPCOUNT);

                loader.remove();
                _Obj.find('.data').show();
                if (_Obj.find('.body tr').length == 0) {
                    _Obj.SuperGrid("MessageBox", "검색조건에 해당되는 자료가 없습니다.");                    
                }


            });
        },

        ShowPage: function (page) {
            pl = $(this).data("filter");
            var JsonForm = $(this).data("formatData");

            pl.add("pagecnt", JsonForm.rowNum);
            pl.add("viewpage", page);
            pl.add("OrderStr", JsonForm.Orderby);
            var loader = jQuery('<div><img src="/image/spinner.gif" /><br>Loading...</div>');
            var _datatable = $(this).data("DataBody")
            var _Obj = $(this);
            _Obj.find('.data').hide();
            loader.prependTo(_Obj.find('.data').parent());
            PostJsonData(JsonForm.ListUr, pl, function (data) {

                var _data = eval("data." + JsonForm.DataName);

                // doSomething(data, _Obj);
                _Obj.SuperGrid("ShowData", _data, data.TRCOUNT, data.VIEWPAGE, data.TPCOUNT);
                //  doSomething(data, _Obj);
                loader.remove();
                _Obj.find('.data').show();
                if (_Obj.find('.body tr').length == 0) {
                    _Obj.SuperGrid("MessageBox", "검색조건에 해당되는 자료가 없습니다.");                    
                }
            });
        },

        SortPage: function (SortField) {
            var JsonForm = $(this).data("formatData");

            var _var = JsonForm.Orderby.split(' ');
            if (SortField == _var[0]) {
                JsonForm.Orderby = SortField + (_var[1] == "ASC" ? " DESC" : " ASC");
            }
            else {
                JsonForm.Orderby = SortField + " ASC";
            }

            $(this).data("formatData", JsonForm);
            this.SuperGrid("ShowPage", 1);
        },

        ShowData: function (JsonData, TRCOUNT, VIEWPAGE, TPCOUNT) {            
            this.SuperGrid("ClearData");
            var JsonForm = $(this).data("formatData");
            var TrData = $(this).data("TRdata");
            var _datatable = $(this).data("DataBody");
            var Rows = JsonData.length;
            $(this).find('.foot table').html("<tr><td style='width:10%' >" + Rows + " Records. </td><td style='width:10%'>0 Selected</td><td style='width:40%'></td><td style='width:40%'></td></tr>");
            if (Rows == 0) { return 0; }

            for (var i = 0; i < Rows; i++) {
                var DataRow = JsonData[i];
                var td = "";
                var newTr = TrData.clone();
                newTr.attr("key", DataRow[JsonForm.keyname]);
                newTr.find('td').each(function (index) {
                    if (index == 0) return true; //continue;

                    var _ftype = $(this).attr('ftype');
                    var _field = $(this).attr('field');
                    var _code = $(this).attr('code');
                    if (_field != "" && _field != undefined) {
                        var data = DataRow[_field];
                    }
                    switch (_ftype) {
                        case 'integer':
                            if (data == "undefined" || data == null || data == "") data = "0";
                            data = number_format(data);
                            $(this).find("input:first").val(data).attr("oldvalue", data);
                            break;
                        case 'string':
                            if (data == "undefined" || data == null || data == "") data = "";
                            $(this).find("input:first").val(data).attr("oldvalue", data);
                            break;
                        case 'combo':
                            if (data == "undefined" || data == null || data == "") data = "";
                            $(this).find("select:first").val(data).attr("oldvalue", data);
                            break;
                        default:
                            if (data == "undefined" || data == null || data == "") data = "&nbsp;";
                            $(this).html(data)
                    }
                });
                newTr.find('td:eq(1)').html(i + 1);
                newTr.find('td:eq(2)').html('R');
                _datatable.find('> tbody').append(newTr);
            }

            if (JsonForm.rowspan) {
                var colCount = JsonForm.colModel.length;
                for (var i = 0; i < colCount; i++) {
                    if (JsonForm.colModel[i].rowspan) _datatable.rowspan(i + 3);
                }
            }
            $(this).find('.foot td:eq(3)').html(String.format(" 총자료수 : {0} /  총페이지수 : {1} / 현재페이지 : {2}", TRCOUNT, TPCOUNT, VIEWPAGE));

            /* page dispplay  --------------------------------------------------- */

            var ViewNum = "";
            var StartPagenum = parseInt((VIEWPAGE - 1) / 10) * 10;
            ViewNum += "<a class='pgNum' pgnum='1'>&nbsp;|&lt;&nbsp;</a>";
            ViewNum += "<a class='pgNum' pgnum='" + (StartPagenum > 10 ? StartPagenum : 1) + "'>&nbsp;&lt;&nbsp;</a>";

            for (i = StartPagenum + 1; i < TPCOUNT * 1 + 1 && i < (StartPagenum * 1 + 11); i++) {
                if (VIEWPAGE * 1 == i) { ViewNum += "<a class='pgNum pgNumNow' pgnum='" + i + "'>&nbsp;" + i + "&nbsp;</a>"; }
                else { ViewNum += "<a class='pgNum' pgnum='" + i + "'>&nbsp;" + i + "&nbsp;</a>"; }
            }

            ViewNum += "<a class='pgNum' pgnum='" + (i < TPCOUNT * 1 + 1 ? StartPagenum + 11 : TPCOUNT) + "'>&nbsp;&gt;&nbsp;</a>";
            ViewNum += "<a class='pgNum' pgnum='" + TPCOUNT + "'>&nbsp;&gt;|&nbsp;</a>";
            $(this).find('.foot td:eq(2)').html(ViewNum);


            var SortField = JsonForm.Orderby.split(' ');

            $(this).find('.head td').removeClass('td_SortAsc').removeClass('td_Sortdesc');
            _obj = $(this).find('.head td[field="' + SortField[0] + '"]');
            var _sortclass = (SortField[1] == "ASC" ? "td_SortAsc" : "td_Sortdesc");
            _obj.addClass(_sortclass);

            this.SuperGrid("BindAction");
            return Rows;
        },

        BindAction: function () {

            var JsonForm = $(this).data("formatData");

            var _datatable = $(this).data("DataBody");
            var _obj = $(this);
            $(this).find('.head td').unbind("click").bind("click", function (e) {
                // 테이블 해드클릭시 정렬시키는 루틴
                if (this.cellIndex == 0) {
                    if ($(this).find('.ChkAll:checkbox:checked').val() == 'checkAll') {
                        _datatable.find('tbody tr').find('> td:first').find('input:checkbox').attr("checked", "checked");
                        _datatable.find('tbody tr').addClass('ui-selected');
                    }
                    else {
                        _datatable.find('tbody tr').find('> td:first').find('input:checkbox').attr("checked", "");
                        _datatable.find('tbody tr').removeClass('ui-selected');
                    }

                    return;
                }
                _field = $(this).attr('field');
                if (_field != undefined) {
                    if (JsonForm.Sort == true) _obj.SuperGrid("SortPage", $(this).attr('field'));
                }
            });

            _datatable.find('> tbody tr').mouseover(function () { $(this).addClass("superGrid_tbody_tr_focus") }).mouseout(function () { $(this).removeClass("superGrid_tbody_tr_focus") });

            _datatable.find('tr').unbind("click").bind("click", function (e) {
                $(this).parent().parent().data("SelectRowIndex", $(this));
                //alert($(this).attr("key"));
            });
            _datatable.find('tr').bind("click", function (e) {
                $(this).parent().find('tr').removeClass('superGrid_tbody_tr_select'); // 행클릭시 모든행의 색상을 white
                $(this).addClass('superGrid_tbody_tr_select'); 					// 행클릭시 선택된 행 색상.
                // 향후 체크박스가 아닌 클릭이벤트동작시에 적용하기로 함
                if (e.ctrlKey) {    //Ctrl+Click  
                    //  $(this).addClass('superGrid_tbody_tr_checked')						// 행클릭시 선택된 행 색상.
                    //  $(this).find('td:eq(0)').find('input').attr("checked", "checked");
                };
            });

            _datatable.find('tr').bind("click", JsonForm.trClick);

            _datatable.find('td').unbind("mouseover").bind("mouseover", JsonForm.tdMouseover);

            //$(this).find('input, select').change(JsonForm.tdChange);
            _datatable.find('td').change(function () {
                if (this.cellIndex == 0) {
                    _cnt = $(this).find('input:checked').length;
                    if (_cnt == 0) {
                        $(this).parent().removeClass('ui-selected');
                    }
                    else {
                        $(this).parent().addClass('ui-selected');
                    }

                    _chkCnt = $(this).parent().parent().find('tr').find('> td:first').find('input:checked').length;
                    $(this).parent().parent().parent().parent().parent().find('> .superGrid_foot td:eq(1)').html(_chkCnt + ' Selected');

                    return;
                }

                var _value = $(this).find(':first-child').val();
                var _oldvalue = $(this).find(':first-child').attr('oldvalue');
                if (_value != _oldvalue)
                    $(this).addClass("changeTD")
                else
                    $(this).removeClass("changeTD")

                // 만일 변경된 내용이 있다면 tr을 업데이트 대상으로 처리한다.
                if ($(this).parent().find(".changeTD").length > 0) {
                    switch ($(this).parent().find('td:eq(2)').html()) {
                        case 'R':
                            $(this).parent().find('td:eq(2)').html('U');
                            $(this).parent().find('td:eq(0)').find('input').attr("checked", "checked");
                            $(this).parent().addClass('superGrid_tbody_tr_checked');
                            break;
                        default:
                    }
                }
                else {
                    switch ($(this).parent().find('td:eq(2)').html()) {
                        case 'U':
                            $(this).parent().find('td:eq(2)').html('R');
                            break;
                        default:
                    }
                }
            });

            _datatable.find('td').change(JsonForm.tdChange);

            $(this).find('.foot .pgNum').mouseover(function () { $(this).addClass("pgNumOver") }).mouseout(function () { $(this).removeClass("pgNumOver") });

            var _obj = $(this);
            $(this).find('.foot .pgNum').unbind("click").bind("click", function (e) {
                _obj.SuperGrid("ShowPage", $(this).attr('pgnum'));
            });


        },

        // 검색결과가 1건인 경우 바로 GridClick 이벤트를 실행함. 2011/02/13 by 최보현
        AddRow: function () {
            var TrData = $(this).data("TRdata").clone();
            var _datatable = $(this).data("DataBody")
            TrData.find('td:eq(2)').html("C");
            _datatable.find('> tbody').append(TrData);
            this.SuperGrid("BindAction");
        },

        DeleteRow: function () {
            var _datatable = $(this).data("DataBody")

            _datatable.find('tr').find('> td:first').find('input:checked').each(function (index) {
                var TrData = $(this).parent().parent();
                var _CRUD = TrData.find('td:eq(2)').html();
                if (_CRUD == "C") { TrData.remove(); }
                if (_CRUD == "R" || _CRUD == "U") { TrData.find('td:eq(2)').html("D"); TrData.hide() }
                if (_CRUD == "D") { TrData.find('td:eq(2)').html("R"); }
            });
        },

        ClearData: function () {
            var _datatable = $(this).data("DataBody");
            _datatable.find('tr').remove();

        },

        // * -- 선택된 row의 필드만 배열로 출력해준다 *//
        GetSelectKey: function () {
            var Keys = new Array();
            $(this).find('.body tr').find('> td:first').find('input:checked').each(function (index) {
                var _tr = $(this).parent().parent();
                var _key = _tr.attr('key');
                Keys[Keys.length] = _key;
            });

            return Keys;

        },

        GetValue: function (key, index, data) {
            var _tr = $(this).find('.superGrid_body tr[key="' + key + '"]');
            var _td = _tr.find('td[field="' + index + '"]');
            return _td.html();

        },

        SetValue: function (key, index, data) {
            var _tr = $(this).find('.superGrid_body tr[key="' + key + '"]');
            var _td = _tr.find('td[field="' + index + '"]');
            _td.html(data);
        },

        GetData: function (JsonData) {
            var RetXml = "<?xml version='1.0' encoding='utf-8' ?><DataTable>";
            $(this).find('.body tr').find('> td:first').find('input:checked').each(function (index) {
                var _tr = $(this).parent().parent();
                var _CRUD = _tr.find('td:eq(2)').html();
                var _key = _tr.attr('key');
                if (_CRUD == 'R') return true;
                if (_CRUD == 'C') _key = 0;
                RetXml += "<Record>";
                RetXml += String.format("<_KEY>{1}</_KEY><_CRUD>{0}</_CRUD>", _CRUD, _key);
                if (_CRUD == 'D') {
                    RetXml += "</Record>";
                    return true;
                }
                var _CRUDFIELD = "";
                _tr.find('td').each(function (index) {
                    var field = $(this).attr("field");
                    if (field == undefined) return true;
                    // 만일 변경된 TD가 아니면 continue
                    if ($(this).hasClass("changeTD")) {
                        _CRUDFIELD += "," + field;
                    }
                    else {
                        return true;
                    }

                    switch ($(this).attr("ftype")) {
                        case 'integer':
                            RetXml += String.format("<{0}>{1}</{0}>", field, $(this).find('> input').val());
                            break;
                        case 'string':
                            RetXml += String.format("<{0}>{1}</{0}>", field, $(this).find('> input').val());
                            break;
                        case 'combo':
                            RetXml += String.format("<{0}>{1}</{0}>", field, $(this).find('> select').val());
                            break;
                        default:
                            RetXml += String.format("<{0}>{1}</{0}>", field, $(this).html());
                    }
                });

                RetXml += "<_CRUDFIELD>" + _CRUDFIELD + "</_CRUDFIELD>";

                RetXml += "</Record>"
            });

            RetXml += "</DataTable>"

            return RetXml;
        },

        GetRowCount: function (options) {
            alert(options + "-" + "옵션입니다");
            return this;

        }
    };
})(jQuery);


(function($){ 
$.fn.rowspan  = function (colIdx) {
    return this.each(function () {

        var that;
        $('tr', this).each(function (row) {
           $('td:eq('+colIdx+')', this).each(function(col) {
                if ($(this).html() == $(that).html()) {
                    rowspan = $(that).attr("rowSpan");
                    if (rowspan == undefined) {
                        $(that).attr("rowSpan", 1);
                        rowspan = $(that).attr("rowSpan");
                    }
                    rowspan = Number(rowspan) + 1;
                    $(that).attr("rowSpan", rowspan); // do your action for the colspan cell here
                    $(this).hide(); // .remove(); // do your action for the old cell here
                } else {
                    that = this;
                }
                that = (that == null) ? this : that; // set the that if not already set
            });
        });

    });
};
})(jQuery);


String.format = function(text) {
    if (arguments.length <= 1) {
        return text;
    }
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }
    return text;
};

//function doSomething(data, _superGrid) {
//    var _data = eval("data." + JsonForm.DataName);

//    _superGrid.SuperGrid("ShowData", _data, data.TRCOUNT, data.VIEWPAGE, data.TPCOUNT);
//} 


$.extend($.expr[':'], {
    focusable: function(element) {
        var nodeName = element.nodeName.toLowerCase(),
		tabIndex = $.attr(element, 'tabindex');

        return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))

        // the element and all of its ancestors must be visible
        // the browser may report that the area is hidden
		&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
    }
});

// 내  용 : 왼쪽부터 string 잘라내기
// 작성자 : 최보현(bhchoi@00db.co.kr)
// 작성일 : 2011/01/11
function Left(String, Length)
{
	if (String == null)
		return (false);

	return String.substr(0, Length);
}